package net.gz01.wallet.web.service;


import java.math.BigDecimal;

import net.gz01.wallet.web.model.FeeModel;

public class CalcFeeService {

	/**
	 * 获取手续费
	 *
	 * @param amount
	 * @param feeId
	 * @return
	 */
	public Integer getFee(Integer amount, Integer feeId) {
		FeeModel f = FeeModel.dao.findById(feeId);
		if (f == null) {
			return -1;
		}
		String rate = f.getRate();
		int maxFee = f.getMaxFee() == null ? 0 : f.getMaxFee();
		int minFee = f.getMinFee() == null ? 0 : f.getMinFee();
		return calcResult(amount, rate, maxFee, minFee);
	}

	/**
	 * 计算结果
	 *
	 * @param amount
	 * @param rate
	 * @param maxFee
	 * @param minFee
	 * @return
	 */
	private Integer calcResult(Integer amount, String rate, Integer maxFee, Integer minFee) {
		Integer minfee = minFee; // 最低
		Integer maxfee = maxFee; // 封顶

		BigDecimal bAmount = new BigDecimal(amount);
		BigDecimal bRate = new BigDecimal(rate);
		// 0.6%，数据库中费率的值是0.6，计算时要除以100
		BigDecimal b100 = new BigDecimal(100);
		BigDecimal temp = bAmount.multiply(bRate).divide(b100).setScale(2, BigDecimal.ROUND_HALF_DOWN);
		int fee = temp.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
		// [最低]手续费
		if (minfee != null && minfee > 0 && fee < minfee) {
			fee = minfee;
		}
		// [封顶]手续费
		if (maxfee != null && maxfee > 0 && fee > maxfee) {
			fee = maxfee;
		}
		// 最低、封顶值设置有误
		if (minfee != null && maxfee != null && maxfee > 0 && minfee > maxfee) {
			return null;
		}
		return fee;
	}
}
